 package photobox.manage

import grails.transaction.Transactional
import grails.validation.ValidationException
import photobox.exception.NotFoundException
import photobox.photo.PhotoFrame
import photobox.utils.HQLUtils

@Transactional
class PhotoFrameService {

    def listPhotoFrame(searchParam, pageParam, sortParam) {
        def hql = ""
        hql += " from PhotoFrame A where 1=1 "
        def params = [:]
        if (searchParam.id) {
            hql += " and " + HQLUtils.whereCondition("A.id", searchParam.id.opt, "id")
            params.id = searchParam.id.data
        }
        if (searchParam.name) {
            hql += " and " + HQLUtils.whereCondition("A.name", searchParam.name.opt, "name")
            params.name = searchParam.name.data
        }
        if (searchParam.description) {
            hql += " and " + HQLUtils.whereCondition("A.description", searchParam.description.opt, "description")
            params.description = searchParam.descriptione.data
        }

        def sortHql = ""
        if (sortParam.sort) {
            sortHql = " order by A.${sortParam.sort} ${sortParam.order} "
        }
        def results = PhotoFrame.executeQuery("select distinct A " + hql + sortHql, params,
                [max: pageParam.pageSize, offset: pageParam.offset])
        def count = PhotoFrame.executeQuery("select count(distinct A.id) " + hql, params)
        return [rs:results, total:count[0]]
    }

    def createFrame(params) {
        def photoFrame = new PhotoFrame()
        photoFrame.name = params.name
        photoFrame.description = params.description
        if(params.isDeal=="on"){
            photoFrame.isDeal = 1
        }else{
            photoFrame.isDeal = 0
        }


        if (!photoFrame.save()) {
            throw new ValidationException("创建相框时发生错误", photoFrame.errors)
        }
    }
    def updateFrame(params){
        def photoFrame = PhotoFrame.get(params.id)
        if(!photoFrame){
            throw new NotFoundException("没有找到对应的相框")
        }
        photoFrame.name = params.name?.trim()
        photoFrame.description = params.description?.trim()
        if(params.isDeal=="on"){
            photoFrame.isDeal = 1
        }else{
            photoFrame.isDeal = 0
        }
        if (!photoFrame.save()) {
            throw new ValidationException("创建相框时发生错误", photoFrame.errors)
        }
    }
    def deleteFrame(params){
        def photoFrame = PhotoFrame.get(params.id)
        if(!photoFrame){
            throw new NotFoundException("没有找到对应的相框")
        }
        photoFrame.delete()
    }
}
